package com.jielihaofeng.chat.service.impl;

import cn.hutool.core.convert.NumberChineseFormatter;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jielihaofeng.chat.constants.ChatUserRelationStatusEnum;
import com.jielihaofeng.chat.constants.MessageTypeEnum;
import com.jielihaofeng.chat.constants.PeriodTypeEnum;
import com.jielihaofeng.chat.convert.ChatMessageConvert;
import com.jielihaofeng.chat.entity.ChatGroupEntity;
import com.jielihaofeng.chat.entity.ChatGroupLocalCacheEntity;
import com.jielihaofeng.chat.entity.ChatMessageEntity;
import com.jielihaofeng.chat.entity.ChatUserRelationEntity;
import com.jielihaofeng.chat.handler.WebSocketNettyHandler;
import com.jielihaofeng.chat.localcache.impl.ChatGroupLocalCache;
import com.jielihaofeng.chat.localcache.impl.SysUserLocalCache;
import com.jielihaofeng.chat.query.ChatMessageQuery;
import com.jielihaofeng.chat.query.SearchUserAndGroupQuery;
import com.jielihaofeng.chat.service.ChatGroupService;
import com.jielihaofeng.chat.service.ChatGroupUserService;
import com.jielihaofeng.chat.service.ChatMessageService;
import com.jielihaofeng.chat.service.ChatUserRelationService;
import com.jielihaofeng.chat.vo.*;
import com.jielihaofeng.framework.common.page.PageResult;
import com.jielihaofeng.framework.common.utils.DateUtils;
import com.jielihaofeng.framework.common.utils.Result;
import com.jielihaofeng.system.entity.SysUserEntity;
import com.jielihaofeng.system.entity.SysUserLocalCacheEntity;
import com.jielihaofeng.system.service.SysUserService;
import com.jielihaofeng.system.vo.SysUserVO;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@AllArgsConstructor
public class ChatService {

    private final SysUserService sysUserService;
    private final ChatUserRelationService chatUserRelationService;
    private final ChatGroupService chatGroupService;
    private final ChatGroupUserService chatGroupUserService;
    private final ChatMessageService chatMessageService;
    private final PasswordEncoder passwordEncoder;
    private final SysUserLocalCache sysUserLocalCache;
    private final ChatGroupLocalCache chatGroupLocalCache;

    // 用户
    // 获取好友列表，指定状态
    public List<Long> getFriendIdListByStatus(Long userId, Integer status) {
        return chatUserRelationService.getFriendIdListByStatus(userId, status);
    }

    /**
     * 获取用户全部好友
     *
     * @param userId 用户ID
     * @return 好友状态
     */
    public Map<Long, Integer> getAllFriendStatus(Long userId) {
        Map<Long, Integer> map = new HashMap<>();
        List<ChatUserRelationEntity> allFriend = chatUserRelationService.getAllFriend(userId);
        allFriend.forEach(relation -> map.put(Objects.equals(relation.getUserId(), userId) ? relation.getFriendId() : relation.getUserId(), relation.getStatus()));
        return map;
    }

    // 添加好友
    public void addFriend(Long userId, Long friendId) {
        chatUserRelationService.addFriend(userId, friendId);
    }

    // 删除好友
    public void deleteFriend(Long userId, Long friendId) {
        chatUserRelationService.deleteFriend(userId, friendId);
    }

    // 群聊
    // 创建群聊
    public void createGroup(ChatGroupVO chatGroupVO) {
        chatGroupService.save(chatGroupVO);
    }

    // 删除群聊
    public void deleteFriend(Long groupId) {
        chatGroupService.delete(groupId);
    }

    // 退出群聊
    public void exitGroup(Long groupId, Long userId) {
        chatGroupUserService.exitGroup(groupId, userId);
    }

    // 群聊所有用户
    public Set<Long> getUserIdList(Long groupId) {
        return chatGroupUserService.getUserIdList(groupId);
    }

    /**
     * 获取用户真实姓名
     *
     * @param userId 用户id
     * @return 用户真实姓名
     */
    public String getUserRealName(Long userId) {
        SysUserLocalCacheEntity sysUserLocalCacheEntity = sysUserLocalCache.get(userId);
        return Optional.ofNullable(sysUserLocalCacheEntity).map(SysUserLocalCacheEntity::getRealName).orElse(null);
    }

    // 消息
    // 发送消息
    public ChatMessageVO sendMessage(ChatMessageVO messageVO) {
        ChatMessageEntity chatMessageEntity = chatMessageService.sendMessage(messageVO);
        ChatMessageVO chatMessageVO = ChatMessageConvert.INSTANCE.convert(chatMessageEntity);
        fillChatMessageVO(chatMessageVO);
        return chatMessageVO;
    }

    // 查询Feed消息列表
    public List<FeedListItemVO> getFeedList(Long userId) {

        // 查询用户所有消息
        List<ChatMessageEntity> messageList = chatMessageService.getAllMessageList(userId);

        // 分组，只需要最晚一条消息
        // 单聊分组：按sender分
        Map<Long, List<ChatMessageEntity>> singleList = messageList.stream()
                .filter(message -> StringUtils.equals(MessageTypeEnum.SINGLE.getCode(), message.getType()))
                .collect(Collectors.groupingBy(msg -> {
                    if (Objects.equals(userId, msg.getSender())) {
                        return msg.getReceiver();
                    } else {
                        return msg.getSender();
                    }
                }));
        // 构建 FeedItemVO
        List<FeedItemVO> singleFeedItemVOList = singleList.entrySet().stream().map(entry -> {
            // 单聊的话这个是发送人的id
            Long sender = entry.getKey();
            List<ChatMessageEntity> list = entry.getValue();

            FeedItemVO feedItemVO = new FeedItemVO();
            feedItemVO.setId(sender);
            // 单聊
            feedItemVO.setType(MessageTypeEnum.SINGLE.getCode());
            // 根据用户id查询用户信息
            SysUserLocalCacheEntity sysUserCacheEntity = sysUserLocalCache.get(sender);
            if (ObjectUtils.isNotEmpty(sysUserCacheEntity)) {
                feedItemVO.setAvatar(sysUserCacheEntity.getAvatar());
                feedItemVO.setName(sysUserCacheEntity.getRealName());
                feedItemVO.setDescription(sysUserCacheEntity.getDescription());
            }
            // 用户在线状态
            feedItemVO.setOnline(webSocketNettyHandler.userOnline(sender));

            feedItemVO.setTag("");
            // 时间处理，取最新一条
            list.stream().max(Comparator.comparing(ChatMessageEntity::getCreateTime))
                    .ifPresent(latestMsg -> {
                        feedItemVO.setPreview(getUserRealName(latestMsg.getSender()) + ": " + latestMsg.getContent());
                        Date date = latestMsg.getCreateTime();
                        feedItemVO.setDate(date);
                        // 计算 period
                        PeriodTypeEnum periodTypeEnum = calculatePeriodType(date);
                        feedItemVO.setPeriod(periodTypeEnum.getName());
                        // 按 period 规则设置时间格式
                        feedItemVO.setTime(calculateTime(periodTypeEnum, date));
                    });
            return feedItemVO;
        }).collect(Collectors.toList());

        // 群聊分组：按receiver分
        Map<Long, List<ChatMessageEntity>> groupList = messageList.stream().filter(message -> StringUtils.equals(MessageTypeEnum.GROUP.getCode(), message.getType())).collect(Collectors.groupingBy(ChatMessageEntity::getReceiver));
        // 构建 FeedItemVO
        List<FeedItemVO> groupFeedItemVOList = groupList.entrySet().stream().map(entry -> {
            // 群聊的话这个是接收人的id，即群组id
            Long receiver = entry.getKey();
            List<ChatMessageEntity> list = entry.getValue();

            FeedItemVO feedItemVO = new FeedItemVO();
            feedItemVO.setId(receiver);
            // 群聊
            feedItemVO.setType(MessageTypeEnum.GROUP.getCode());
            // 根据群组id查询群组信息：群组头像、名称、群组简介
            ChatGroupLocalCacheEntity chatGroupCacheEntity = chatGroupLocalCache.get(receiver);
            if (ObjectUtils.isNotEmpty(chatGroupCacheEntity)) {
                feedItemVO.setAvatar(chatGroupCacheEntity.getAvatar());
                feedItemVO.setName(chatGroupCacheEntity.getName());
                feedItemVO.setDescription(chatGroupCacheEntity.getDescription());
            }

            feedItemVO.setTag("群组");
            // 取最新一条，时间转字符串
            list.stream().max(Comparator.comparing(ChatMessageEntity::getCreateTime))
                    .ifPresent(latestMsg -> {
                        feedItemVO.setPreview(getUserRealName(latestMsg.getSender()) + ": " + latestMsg.getContent());
                        Date date = latestMsg.getCreateTime();
                        PeriodTypeEnum periodTypeEnum = calculatePeriodType(date);
                        feedItemVO.setDate(date);
                        feedItemVO.setPeriod(periodTypeEnum.getName());
                        feedItemVO.setTime(calculateTime(periodTypeEnum, date));
                    });
            return feedItemVO;
        }).collect(Collectors.toList());

        // 组合，按 period 分组，按时间排序
        LinkedHashMap<String, List<FeedItemVO>> collect = Stream.concat(singleFeedItemVOList.stream(), groupFeedItemVOList.stream())
                .sorted(Comparator.comparing(FeedItemVO::getDate).reversed())
                .collect(Collectors.groupingBy(FeedItemVO::getPeriod, LinkedHashMap::new, Collectors.toList()));
        return collect.entrySet()
                .stream()
                .map(entry -> new FeedListItemVO().setPeriod(entry.getKey())
                        .setFeedItems(entry.getValue()))
                .collect(Collectors.toList());
    }

    /**
     * 获取消息列表
     *
     * @param query 查询参数
     * @return 消息列表
     */
    public PageResult<ChatMessageVO> getMessageList(ChatMessageQuery query) {
        PageResult<ChatMessageEntity> messageListPage = chatMessageService.getMessageList(query);
        List<ChatMessageVO> chatMessageVOList = ChatMessageConvert.INSTANCE.convertList(messageListPage.getList());
        // 补充数据
        chatMessageVOList.forEach(chatMessageVO -> {
            // 填充 ChatMessageVO
            fillChatMessageVO(chatMessageVO);
        });
        return new PageResult<>(chatMessageVOList, messageListPage.getTotal());
    }

    /**
     * 填充 ChatMessageVO
     *
     * @param chatMessageVO 聊天消息VO
     */
    private void fillChatMessageVO(ChatMessageVO chatMessageVO) {
        // 发送人头像
        Long sender = chatMessageVO.getSender();
        SysUserEntity userEntity = sysUserService.getById(sender);
        chatMessageVO.setAvatar(userEntity.getAvatar());
        // 时间处理
        Date date = chatMessageVO.getCreateTime();
        PeriodTypeEnum periodTypeEnum = calculatePeriodType(date);
        chatMessageVO.setTime(calculateTime(periodTypeEnum, date));
    }

    /**
     * 计算时间字符串
     *
     * @param periodTypeEnum 时期类型
     * @param date           时间
     * @return 时间字符串
     */
    private String calculateTime(PeriodTypeEnum periodTypeEnum, Date date) {

        switch (periodTypeEnum) {
            case TODAY:
                return DateUtils.getDuringDay(date) + DateUtils.format(date, "H:mm");
            case YESTERDAY:
                return periodTypeEnum.getName() + " " + DateUtils.getDuringDay(date) + DateUtils.format(date, "H:mm");
            case THIS_WEEK:
                int weekDay = DateUtil.dayOfWeek(date);
                String chineseWeekDay = weekDay == 0 ? "天" : NumberChineseFormatter.format(DateUtil.dayOfWeek(date), false, false);
                return "星期" + chineseWeekDay + " " + DateUtils.getDuringDay(date) + DateUtils.format(date, "H:mm");
            case THIS_MONTH:
            case THIS_YEAR:
                return DateUtils.format(date, "M月d日") + " " + DateUtils.format(date, "H:mm");
            case EARLIER:
                return DateUtils.format(date, "yyyy年M月d日") + " " + DateUtils.format(date, "H:mm");
        }
        return null;
    }

    /**
     * 计算日期所在时期
     *
     * @param date 时间
     * @return 时期
     */
    private PeriodTypeEnum calculatePeriodType(Date date) {

        Date now = new Date();
        // 如果日期等于今天
        if (DateUtil.isSameDay(now, date)) {
            return PeriodTypeEnum.TODAY;
        }
        // 如果是昨天
        DateTime yesterday = DateUtil.yesterday();
        if (DateUtil.isSameDay(yesterday, date)) {
            return PeriodTypeEnum.YESTERDAY;
        }
        // 如果是本周
        if (DateUtil.isSameWeek(now, date, true)) {
            return PeriodTypeEnum.THIS_WEEK;
        }
        // 如果是本月
        if (DateUtil.isSameMonth(now, date)) {
            return PeriodTypeEnum.THIS_MONTH;
        }
        // 日期等于今年
        if (DateUtils.isSameYear(now, date)) {
            return PeriodTypeEnum.THIS_YEAR;
        }

        // 否则默认为更早
        return PeriodTypeEnum.EARLIER;
    }


    @Autowired
    private WebSocketNettyHandler webSocketNettyHandler;

    /**
     * 获取好友和群组列表VO
     */
    public FriendAndGroupVO getFriendAndGroupList(Long userId) {
        FriendAndGroupVO friendAndGroupVO = new FriendAndGroupVO();
        // 所有好友
        List<Long> friendIdListByStatus = chatUserRelationService.getFriendIdListByStatus(userId, ChatUserRelationStatusEnum.ALREADY.getCode());
        // 好友在线情况
        Map<Long, Boolean> userOnlineMap = webSocketNettyHandler.getUserOnlineMap(friendIdListByStatus);
        Long count = userOnlineMap.values().stream().filter(value -> Boolean.TRUE == value).count();
        friendAndGroupVO.setOnlineNum(count.intValue());
        List<FriendAndGroupItemVO> friendList = friendIdListByStatus
                .stream()
                .map(uid -> {
                    FriendAndGroupItemVO friendAndGroupItemVO = new FriendAndGroupItemVO();
                    friendAndGroupItemVO.setId(uid);
                    // 根据用户id查询用户信息：头像、姓名、个性签名
                    SysUserEntity sysUserEntity = sysUserService.getById(uid);
                    if (ObjectUtils.isNotEmpty(sysUserEntity)) {
                        friendAndGroupItemVO.setAvatar(sysUserEntity.getAvatar());
                        friendAndGroupItemVO.setName(sysUserEntity.getRealName());
                        friendAndGroupItemVO.setDescription(sysUserEntity.getDescription());
                    }
                    friendAndGroupItemVO.setTag("");
                    friendAndGroupItemVO.setType(MessageTypeEnum.SINGLE.getCode());
                    friendAndGroupItemVO.setOnline(userOnlineMap.get(uid));
                    return friendAndGroupItemVO;
                })
                // 好友列表排序，在线好友排在前面
                .sorted((pre, next) -> pre.getOnline() ^ next.getOnline() ? (pre.getOnline() ? -1 : 1) : 0)
                .collect(Collectors.toList());
        friendAndGroupVO.setFriendList(friendList);

        // 所有群组
        List<Long> groupIdList = chatGroupUserService.getGroupIdList(userId);
        // 群组
        List<FriendAndGroupItemVO> groupList = groupIdList.stream().map(uid -> {
            FriendAndGroupItemVO friendAndGroupItemVO = new FriendAndGroupItemVO();
            friendAndGroupItemVO.setId(uid);
            // 根据群组id查询用户信息：头像、群组名、群组简介
            ChatGroupEntity chatGroupEntity = chatGroupService.getById(uid);
            if (ObjectUtils.isNotEmpty(chatGroupEntity)) {
                friendAndGroupItemVO.setAvatar(chatGroupEntity.getAvatar());
                friendAndGroupItemVO.setName(chatGroupEntity.getName());
                friendAndGroupItemVO.setDescription(chatGroupEntity.getDescription());
            }
            friendAndGroupItemVO.setTag("");
            friendAndGroupItemVO.setType(MessageTypeEnum.GROUP.getCode());
            friendAndGroupItemVO.setOnline(userOnlineMap.get(uid));
            return friendAndGroupItemVO;
        }).collect(Collectors.toList());
        friendAndGroupVO.setGroupList(groupList);

        return friendAndGroupVO;
    }

    /**
     * 搜索用户和群组
     *
     * @param query
     * @return
     */
    public SearchUserAndGroupVO searchUserAndGroup(SearchUserAndGroupQuery query) {
        SearchUserAndGroupVO searchUserAndGroupVO = new SearchUserAndGroupVO();
        String searchKey = query.getSearchKey();
        // 1.1 查询用户列表
        LambdaQueryChainWrapper<SysUserEntity> userQueryWrapper = sysUserService.lambdaQuery()
                .like(SysUserEntity::getRealName, searchKey)
                .or().like(SysUserEntity::getEmail, searchKey)
                .or().like(SysUserEntity::getMobile, searchKey);
        Page<SysUserEntity> page = sysUserService.page(Page.of(query.getPage(), query.getLimit()), userQueryWrapper);
        // 1.2 查询自己的好友列表
        Map<Long, Integer> allFriend = getAllFriendStatus(query.getUserId());
        // 1.3 构建用户列表
        List<FriendAndGroupItemVO> userList = page.getRecords().stream().map(user ->
                        new FriendAndGroupItemVO()
                                .setId(user.getId())
                                .setName(user.getRealName())
                                .setAvatar(user.getAvatar())
                                .setDescription(user.getDescription())
                                .setType(MessageTypeEnum.SINGLE.getCode())
                                .setOnline(webSocketNettyHandler.userOnline(user.getId()))
                                .setTag("")
                                .setEmail(user.getEmail())
                                .setMobile(user.getMobile())
                                .setStatus(allFriend.get(user.getId()))
                )
                .collect(Collectors.toList());
        searchUserAndGroupVO.setUserList(userList);

        // 2.1 查询群组列表
        LambdaQueryChainWrapper<ChatGroupEntity> groupQueryWrapper = chatGroupService.lambdaQuery().like(ChatGroupEntity::getName, searchKey);
        Page<ChatGroupEntity> groupEntityPage = chatGroupService.page(Page.of(query.getPage(), query.getLimit()), groupQueryWrapper);
        // 2.2 查询自己的群组列表
        List<Long> groupIdList = chatGroupUserService.getGroupIdList(query.getUserId());
        // 2.3 构建群组列表
        List<FriendAndGroupItemVO> groupList = groupEntityPage.getRecords().stream().map(group ->
                new FriendAndGroupItemVO()
                        .setId(group.getId())
                        .setName(group.getName())
                        .setAvatar(group.getAvatar())
                        .setDescription(group.getDescription())
                        .setType(MessageTypeEnum.SINGLE.getCode())
                        .setTag("")
                        .setStatus(groupIdList.contains(group.getId()) ? 1 : null)
        ).collect(Collectors.toList());
        searchUserAndGroupVO.setGroupList(groupList);

        Boolean isFriend = Optional.ofNullable(query.getIsFriend()).orElse(false);
        if (isFriend) {
            // 好友列表的查询

        } else {
            // 添加好友的查询

        }
        return searchUserAndGroupVO;
    }

    public List<FriendAndGroupItemVO> searchUserList(SearchUserAndGroupQuery query) {
        String searchKey = query.getSearchKey();
        // 1.1 查询用户列表
        LambdaQueryWrapper<SysUserEntity> userQueryWrapper = new LambdaQueryWrapper<SysUserEntity>()
                .ne(SysUserEntity::getId, query.getUserId())
                .and(wrapper -> wrapper.like(SysUserEntity::getRealName, searchKey)
                        .or(w1 -> w1.like(SysUserEntity::getEmail, searchKey))
                        .or(w2 -> w2.like(SysUserEntity::getMobile, searchKey)));

        List<SysUserEntity> list = sysUserService.list(userQueryWrapper);
//        Page<SysUserEntity> page = sysUserService.page(Page.of(query.getPage(), query.getLimit()), userQueryWrapper);
        // 1.2 查询自己的好友列表
        Map<Long, Integer> allFriend = getAllFriendStatus(query.getUserId());
        // 1.3 构建用户列表
        List<FriendAndGroupItemVO> userList = list.stream().map(user ->
                        new FriendAndGroupItemVO()
                                .setId(user.getId())
                                .setName(user.getRealName())
                                .setAvatar(user.getAvatar())
                                .setDescription(user.getDescription())
                                .setType(MessageTypeEnum.SINGLE.getCode())
                                .setOnline(webSocketNettyHandler.userOnline(user.getId()))
                                .setTag("")
                                .setEmail(user.getEmail())
                                .setMobile(user.getMobile())
                                .setStatus(allFriend.get(user.getId()))
                )
                .collect(Collectors.toList());
        Boolean isFriend = Optional.ofNullable(query.getIsFriend()).orElse(false);
        if (isFriend) {
            // 好友列表的查询

        } else {
            // 添加好友的查询

        }
        return userList;
    }

    public List<FriendAndGroupItemVO> searchGroupList(SearchUserAndGroupQuery query) {
        String searchKey = query.getSearchKey();
        // 2.1 查询群组列表
        LambdaQueryWrapper<ChatGroupEntity> groupQueryWrapper = new LambdaQueryWrapper<ChatGroupEntity>().like(ChatGroupEntity::getName, searchKey);
        Page<ChatGroupEntity> groupEntityPage = chatGroupService.page(Page.of(query.getPage(), query.getLimit()), groupQueryWrapper);
        // 2.2 查询自己的群组列表
        List<Long> groupIdList = chatGroupUserService.getGroupIdList(query.getUserId());
        // 2.3 构建群组列表
        List<FriendAndGroupItemVO> groupList = groupEntityPage.getRecords().stream().map(group ->
                new FriendAndGroupItemVO()
                        .setId(group.getId())
                        .setName(group.getName())
                        .setAvatar(group.getAvatar())
                        .setDescription(group.getDescription())
                        .setType(MessageTypeEnum.SINGLE.getCode())
                        .setTag("")
                        .setStatus(groupIdList.contains(group.getId()) ? 1 : null)
        ).collect(Collectors.toList());
        return groupList;
    }


    /**
     * 添加好友，发送好友申请
     *
     * @param chatUserRelationVO
     * @return
     */
    public boolean addFriend(ChatUserRelationVO chatUserRelationVO) {
        return chatUserRelationService.save(chatUserRelationVO);
    }

    /**
     * 加入群组
     *
     * @param chatGroupUserVO
     * @return
     */
    public boolean joinGroup(ChatGroupUserVO chatGroupUserVO) {
        return chatGroupUserService.save(chatGroupUserVO);
    }

    /**
     * 申请好友列表
     *
     * @param userId 用户ID
     * @return
     */
    public List<FriendAndGroupItemVO> getRequestFriendList(Long userId) {
        List<Long> list = chatUserRelationService.getRequestFriendIdList(userId);
        // 1.3 构建用户列表
        List<FriendAndGroupItemVO> userList = list.stream().map(uid -> {
                    SysUserEntity user = sysUserService.getById(uid);
                    return new FriendAndGroupItemVO()
                            .setId(user.getId())
                            .setName(user.getRealName())
                            .setAvatar(user.getAvatar())
                            .setDescription(user.getDescription())
                            .setType(MessageTypeEnum.SINGLE.getCode())
                            // 这里可以不查的
                            .setOnline(webSocketNettyHandler.userOnline(user.getId()))
                            .setTag("")
                            .setEmail(user.getEmail())
                            .setMobile(user.getMobile())
                            .setStatus(ChatUserRelationStatusEnum.READY.getCode());
                })
                .collect(Collectors.toList());
        return userList;
    }

    public boolean receiveFriendRequest(Long userId, Long friendId) {
        ChatUserRelationEntity chatUserRelationEntity = chatUserRelationService.queryByUserIdAndFriendId(userId, friendId);
        if (chatUserRelationEntity != null) {
            chatUserRelationEntity.setStatus(1);
            return chatUserRelationService.updateById(chatUserRelationEntity);
        }
        return false;
    }

    public boolean rejectFriendRequest(Long userId, Long friendId) {
        return chatUserRelationService.deleteFriend(userId, friendId);
    }

    @Transactional
    public Result register(SysUserVO sysUserVO) {
        String username = sysUserVO.getUsername();
        SysUserEntity byUsername = sysUserService.getByUsername(username);
        if (byUsername != null) {
            return Result.error("用户名已存在");
        }
        sysUserVO.setPassword(passwordEncoder.encode(sysUserVO.getPassword()));
        sysUserVO.setStatus(1);
        sysUserVO.setSuperAdmin(0);
        sysUserVO.setGender(2);
        sysUserVO.setOrgId(20L);
        sysUserVO.setRoleIdList(Collections.singletonList(2L));
        sysUserVO.setPostIdList(Collections.singletonList(9L));
        sysUserVO.setAvatar("https://q.qlogo.cn/g?b=qq&nk=604694058&s=100");
        sysUserService.save(sysUserVO);

        // 客服添加新用户为好友
        SysUserEntity currentUser = sysUserService.getByUsername(username);
        ChatUserRelationVO chatUserRelationVO = new ChatUserRelationVO();
        chatUserRelationVO.setUserId(10000L);
        chatUserRelationVO.setFriendId(currentUser.getId());
        chatUserRelationVO.setStatus(1);
        chatUserRelationService.save(chatUserRelationVO);
        // 客服默认发送消息
        ChatMessageEntity chatMessageEntity = new ChatMessageEntity();
        chatMessageEntity.setSender(10000L);
        chatMessageEntity.setReceiver(currentUser.getId());
        chatMessageEntity.setStatus(0);
        chatMessageEntity.setContent(sysUserVO.getRealName() + "，感谢您注册并使用拖油，今后有任何不爽的都可以跟拖油油吐槽哦~");
        chatMessageEntity.setType(MessageTypeEnum.SINGLE.getCode());
        chatMessageService.save(chatMessageEntity);

        // 加入用户交流群
        ChatGroupUserVO chatGroupUserVO = new ChatGroupUserVO();
        chatGroupUserVO.setUserId(currentUser.getId());
        chatGroupUserVO.setGroupId(1L);
        joinGroup(chatGroupUserVO);

        // 客服通知大家新成员加入
        ChatMessageEntity groupChatMessageEntity = new ChatMessageEntity();
        groupChatMessageEntity.setSender(10000L);
        groupChatMessageEntity.setReceiver(1L);
        groupChatMessageEntity.setStatus(0);
        groupChatMessageEntity.setContent("欢迎新用户@"+sysUserVO.getRealName()+" 加入群聊，快跟大家打个招呼吧~");
        groupChatMessageEntity.setType(MessageTypeEnum.GROUP.getCode());
        chatMessageService.save(groupChatMessageEntity);
        return Result.ok();
    }
}